package com.example.gokuplayalong.service.fragmentsmanage;

import android.content.Context;
import android.view.KeyEvent;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.example.gokuplayalong.MainActivity;
import com.example.gokuplayalong.R;
import com.example.gokuplayalong.bases.alipay.directpay.DirectPayMerchantCreate;
import com.example.gokuplayalong.bases.beans.AppParams;
import com.example.gokuplayalong.bases.exception.ExceptionUtils;
import com.example.gokuplayalong.bases.tools.Logger;
import com.example.gokuplayalong.service.fragments.users.message.UserMainMessageServiceNotify;
import com.example.gokuplayalong.service.fragments.users.others.UserMainChat;
import com.example.gokuplayalong.service.fragments.users.profile.UserMainProfileApplication;
import com.example.gokuplayalong.service.fragments.users.profile.UserMainProfileBalanceDetail;
import com.example.gokuplayalong.service.fragments.users.profile.UserMainProfileInfo;
import com.example.gokuplayalong.service.fragments.users.profile.UserMainProfileLogout;
import com.example.gokuplayalong.service.fragments.users.profile.UserMainProfileMerchantInfo;
import com.example.gokuplayalong.service.fragments.users.profile.UserMainProfileMoreSetting;
import com.example.gokuplayalong.service.fragments.users.profile.UserMainProfileMyOrder;
import com.example.gokuplayalong.service.fragments.users.profile.UserMainProfileMyOrderException;
import com.example.gokuplayalong.service.fragments.users.profile.UserMainProfileOnlineCustom;
import com.example.gokuplayalong.service.fragments.users.profile.UserMainProfileServiceTerms;
import com.example.gokuplayalong.service.fragments.users.receive.UserMainReceiveList;
import com.example.gokuplayalong.service.fragments.users.receive.UserMainReceiveOrderDetail;
import com.example.gokuplayalong.service.fragments.users.receive.UserMainReceiveUserInfo;
import com.example.gokuplayalong.service.fragments.users.receive.UserMainReceiveUserInfoAddSkills;
import com.example.gokuplayalong.service.fragments.users.receive.UserMainReceiveUserInfoPlaceOrder;
import com.example.gokuplayalong.service.home.HomeLogin;
import com.example.gokuplayalong.service.home.HomeMain;
import com.example.gokuplayalong.service.home.HomeShow;
import com.kongzue.dialogx.dialogs.PopTip;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Semaphore;

public class SysManagerFragments {


    Context context;
    static long exitTime = 0;

    static Semaphore semaphore = new Semaphore(1);

    public SysManagerFragments() {
    }

    public SysManagerFragments(Context context) {
        this.context = context;
    }

    public static void add(int id, FragmentManager fragmentManager, Fragment fragment, String tag) {
        if (fragment != null)
            fragmentManager.beginTransaction().add(id, fragment, tag).hide(fragment).commit();
    }

    public static boolean addAndShow(int id, FragmentManager fragmentManager, Fragment fragment, String tag) {
        if (fragment != null) {
            fragmentManager.beginTransaction().add(id, fragment, tag).hide(fragment).commit();
            fragmentManager.beginTransaction().show(fragment).commit();

            return true;
        }
        return false;

    }


    public static void hide(FragmentManager fragmentManager, Fragment fragment) {
        if (fragment != null)
            fragmentManager.beginTransaction().hide(fragment).commitAllowingStateLoss();
    }

    public static void show(FragmentManager fragmentManager, Fragment fragment) {
        if (fragment != null) {
            fragmentManager.beginTransaction().show(fragment).commitAllowingStateLoss();
        }
    }

    public static void hideShow(FragmentManager fragmentManager, Fragment fragment) {
        if (fragment != null)
            fragmentManager.beginTransaction().hide(fragment).show(fragment).commit();
    }

    public static void switchs(FragmentManager fragmentManager, String from, String to) {
        Fragment fragment1 = fragmentManager.findFragmentByTag(from);
        Fragment fragment2 = fragmentManager.findFragmentByTag(to);
        if (fragment1 != null && fragment2 != null) {
            fragmentManager.beginTransaction().hide(fragment1).show(fragment2).commit();
        }
    }

    public static void switchs(FragmentManager fragmentManager, Fragment from, Fragment to) {
        if (from != null && to != null)
            fragmentManager.beginTransaction().hide(from).show(to).commit();
    }

    public static void addToSysFragment(Fragment fragment, String tag) {
        add(R.id.main_blank_fragment, AppParams.getInstance().sysfragmentmanager, fragment, tag);
    }

    public static void addToSysFragmentAndShow(Fragment fragment, String tag) {
        if (addAndShow(R.id.main_blank_fragment, AppParams.getInstance().sysfragmentmanager, fragment, tag) && !Objects.equals(tag, "HomeShow")) {
            AppParams.getInstance().fragments.add(tag);
            AppParams.getInstance().currentFragment++;
        }

    }


    public static void switchOnSysFragmentThree(String to) {
        try {
            semaphore.acquire();
            Fragment fragment = AppParams.getInstance().sysfragmentmanager.findFragmentByTag(to);
            List<Fragment> fragments = AppParams.getInstance().sysfragmentmanager.getFragments();
            for (Fragment f : fragments) {
                if (f != null && f.isVisible()) {
                    hide(AppParams.getInstance().sysfragmentmanager, f);
                }
            }
            show(AppParams.getInstance().sysfragmentmanager, fragment);
            if (!AppParams.getInstance().fragments.isEmpty())
                AppParams.getInstance().fragments.clear();
            AppParams.getInstance().fragments.add("HomeShow");
            AppParams.getInstance().fragments.add("HomeLogin");
            AppParams.getInstance().fragments.add("HomeMain");
            AppParams.getInstance().currentFragment = AppParams.getInstance().fragments.indexOf(to);

//            PopTip.show(Arrays.toString(AppParams.getInstance().fragments.toArray()));
            semaphore.release();
        } catch (Throwable e) {
            semaphore.release();
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }

    }

    public static void switchOnSysFragment(String to) {
        try {
            semaphore.acquire();
            Fragment fragment = AppParams.getInstance().sysfragmentmanager.findFragmentByTag(to);
            List<Fragment> fragments = AppParams.getInstance().sysfragmentmanager.getFragments();
            for (Fragment f : fragments) {
                if (f != null && f.isVisible()) {
                    hide(AppParams.getInstance().sysfragmentmanager, f);
                }
            }
            if (AppParams.getInstance().currentFragment < 3)
                AppParams.getInstance().currentFragment = 2;
            show(AppParams.getInstance().sysfragmentmanager, fragment);
            AppParams.getInstance().fragments.add(to);
            AppParams.getInstance().currentFragment++;

            semaphore.release();
        } catch (Throwable e) {
            semaphore.release();
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }

    public static void clearAllToMain() {

        if (!AppParams.getInstance().fragments.isEmpty()) AppParams.getInstance().fragments.clear();
        Fragment fragment = AppParams.getInstance().sysfragmentmanager.findFragmentByTag("HomeShow");
        if (fragment == null || !fragment.isAdded()) {
            SysManagerFragments.addToSysFragment(new HomeShow(), "HomeShow");
        }
        fragment = AppParams.getInstance().sysfragmentmanager.findFragmentByTag("HomeMain");
        if (fragment == null || !fragment.isAdded()) {
            SysManagerFragments.addToSysFragment(new HomeMain(), "HomeMain");
        }
        AppParams.getInstance().fragments.add("HomeShow");
        AppParams.getInstance().fragments.add("HomeMain");
        AppParams.getInstance().currentFragment = 1;
    }

    public static void clearRepeatOnSysFragment() {
        List<String> temp = new ArrayList<>();
        for (int i = 0; i < AppParams.getInstance().fragments.size(); i++) {
            if (temp.isEmpty()) {
                temp.add(AppParams.getInstance().fragments.get(i));
            }
            else {
                int j = 0;
                for (j = 0; j < temp.size(); j++) {
                    if (Objects.equals(AppParams.getInstance().fragments.get(i), temp.get(j))) {
                        break;
                    }
                }
                if (j == temp.size()) {
                    temp.add(AppParams.getInstance().fragments.get(i));
                }
            }
        }
        AppParams.getInstance().fragments = new ArrayList<>(temp);
        AppParams.getInstance().currentFragment = AppParams.getInstance().fragments.size() - 1;

        Logger.d("after : " + AppParams.getInstance().fragments.toString());

    }

    public static void showAfterHideOnSysFragment(String to) {
        Fragment fragment = AppParams.getInstance().sysfragmentmanager.findFragmentByTag(to);
        if (fragment != null) {
            hide(AppParams.getInstance().sysfragmentmanager, fragment);
            show(AppParams.getInstance().sysfragmentmanager, fragment);
        }
    }

    public static void switchNewlyBuiltOnSysFragment(String to, Fragment newFragment) {
        try {
            semaphore.acquire();
            Fragment fragment = AppParams.getInstance().sysfragmentmanager.findFragmentByTag(to);

            if (fragment != null) {
                AppParams.getInstance().sysfragmentmanager.beginTransaction()
                        .remove(fragment)
                        .commit();
            }
            addToSysFragmentAndShow(newFragment, to);
            semaphore.release();
        } catch (Throwable e) {
            semaphore.release();
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }

    public static void switchNewlyBuiltOnSysFragment(String from, String to, Fragment newFragment) {
        Fragment fragment = AppParams.getInstance().sysfragmentmanager.findFragmentByTag(to);

        if (fragment != null) {
            AppParams.getInstance().sysfragmentmanager.beginTransaction().remove(fragment).commit();
        }
        fragment = AppParams.getInstance().sysfragmentmanager.findFragmentByTag(from);
        if (fragment != null) {
            AppParams.getInstance().sysfragmentmanager.beginTransaction().hide(fragment).commit();

        }
        addToSysFragmentAndShow(newFragment, to);
    }

    public static void switchBackOnSysFragment() {

        try {
            semaphore.acquire();
            if (AppParams.getInstance().currentFragment <= AppParams.getInstance().fragments.size() && AppParams.getInstance().currentFragment > 0) {
                Fragment from = AppParams.getInstance().sysfragmentmanager.findFragmentByTag(AppParams.getInstance().fragments.get(AppParams.getInstance().currentFragment));
                if (from != null) {
                    AppParams.getInstance().fragments.remove(AppParams.getInstance().currentFragment);
                    AppParams.getInstance().currentFragment--;
                    Fragment to = AppParams.getInstance().sysfragmentmanager.findFragmentByTag(AppParams.getInstance().fragments.get(AppParams.getInstance().currentFragment));
                    if (to != null) {
                        AppParams.getInstance().sysfragmentmanager.beginTransaction()
                                .hide(from)
                                .show(to)
                                .commitNow();
                    }
                }
            }
            semaphore.release();
        } catch (Throwable e) {
            semaphore.release();
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }

    public static void jumpOnSysFragment(String str) {

        List<String> strings = new ArrayList<>();
        int first = AppParams.getInstance().fragments.indexOf(str);
        if (first > 0) {
            for (int i = 0; i < first; i++) {
                strings.add(AppParams.getInstance().fragments.get(i));
            }
            AppParams.getInstance().fragments = new ArrayList<>(strings);
            AppParams.getInstance().currentFragment = AppParams.getInstance().fragments.size() - 1;
            switchOnSysFragment(str);
        }
    }

    public static void checkRepeatOpen(String f, int t, String way) {
        int count = 0;
        int index = 0;
        for (int i = 0; i < AppParams.getInstance().fragments.size(); i++) {
            if (AppParams.getInstance().fragments.get(i).equals(f)) {
                count++;
                if (count == t) index = i;
            }
        }
        Logger.d("/*************/");
        Logger.d("count : " + count);
        Logger.d(AppParams.getInstance().fragments.toString());
        Logger.d(index + "");
        List<String> strings = new ArrayList<>();
        if (count >= t) {
            for (int i = 0; i < index + 1; i++) {
                strings.add(AppParams.getInstance().fragments.get(i));
            }
            AppParams.getInstance().fragments = new ArrayList<>(strings);
            AppParams.getInstance().currentFragment = AppParams.getInstance().fragments.size() - 1;
        }
        Logger.d(AppParams.getInstance().fragments.toString());
        Logger.d("/*******************/");
    }

    public static void checkRepeatOpen(String f, int t) {
        int count = 0;
        int index = 0;
        for (int i = 0; i < AppParams.getInstance().fragments.size(); i++) {
            if (AppParams.getInstance().fragments.get(i).equals(f)) {
                count++;
                if (count == t) index = i;
            }

        }
//        Logger.d("/*************/");
//        Logger.d("count : " + count);
//        Logger.d(AppParams.getInstance().fragments.toString());
//        Logger.d(index + "");
        List<String> strings = new ArrayList<>();
        if (count >= t) {
            for (int i = 0; i < index + 1; i++) {
                strings.add(AppParams.getInstance().fragments.get(i));
            }
            AppParams.getInstance().fragments = new ArrayList<>(strings);
            AppParams.getInstance().currentFragment = AppParams.getInstance().fragments.size() - 1;
        }
//        Logger.d(AppParams.getInstance().fragments.toString());
//        Logger.d("/*******************/");
    }

    public static void init(FragmentManager fragmentManager) {
        try {
            if (!AppParams.getInstance().fragments.isEmpty())
                AppParams.getInstance().fragments.clear();
            AppParams.getInstance().fragments.add("HomeShow");
            AppParams.getInstance().fragments.add("HomeLogin");
            AppParams.getInstance().fragments.add("HomeMain");
            AppParams.getInstance().sysfragmentmanager = fragmentManager;
            AppParams.getInstance().currentFragment = 0;
            SysManagerFragments.initFragments();

        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }

    public static Boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (AppParams.getInstance().currentFragment > 2) {
                SysManagerFragments.switchBackOnSysFragment();
            }
            else {
                if (System.currentTimeMillis() - exitTime < 500) {

                    exitTime = System.currentTimeMillis();
                    MainActivity.getInstance().moveTaskToBack(true);

                }
                else {
                    PopTip.show("再按一次退出程序");
                    exitTime = System.currentTimeMillis();
                }

            }
            return true;
        }
        return false;
    }

    public static void initFragments() {
        try {
            SysManagerFragments.addToSysFragmentAndShow(new HomeShow(), "HomeShow");
            SysManagerFragments.addToSysFragment(new HomeMain(), "HomeMain");
            SysManagerFragments.addToSysFragment(new HomeLogin(), "HomeLogin");
            SysManagerFragments.addToSysFragment(new UserMainMessageServiceNotify(), "UserMainMessageServiceNotify");
            SysManagerFragments.addToSysFragment(new UserMainReceiveList(), "UserMainReceiveList");
            SysManagerFragments.addToSysFragment(new UserMainProfileMerchantInfo(), "UserMainProfileMerchantInfo");
            SysManagerFragments.addToSysFragment(new UserMainReceiveUserInfo(), "UserMainReceiveUserInfo");
            SysManagerFragments.addToSysFragment(new UserMainProfileApplication(), "UserMainProfileApplication");
            SysManagerFragments.addToSysFragment(new UserMainProfileMyOrder(), "UserMainProfileMyOrder");
            SysManagerFragments.addToSysFragment(new UserMainReceiveOrderDetail(), "UserMainReceiveOrderDetail");
            SysManagerFragments.addToSysFragment(new UserMainProfileOnlineCustom(), "UserMainProfileOnlineCustom");
            SysManagerFragments.addToSysFragment(new UserMainChat(), "UserMainChat");
            SysManagerFragments.addToSysFragment(new UserMainProfileBalanceDetail(), "UserMainProfileBalanceDetail");
            SysManagerFragments.addToSysFragment(new UserMainProfileMoreSetting(), "UserMainProfileMoreSetting");
            SysManagerFragments.addToSysFragment(new UserMainProfileServiceTerms(), "UserMainProfileServiceTerms");
            SysManagerFragments.addToSysFragment(new UserMainProfileLogout(), "UserMainProfileLogout");
            SysManagerFragments.addToSysFragment(new UserMainReceiveUserInfoPlaceOrder(), "UserMainReceiveUserInfoPlaceOrder");
            SysManagerFragments.addToSysFragment(new UserMainReceiveUserInfoAddSkills(), "UserMainReceiveUserInfoAddSkills");
            SysManagerFragments.addToSysFragment(new UserMainProfileInfo(), "UserMainProfileInfo");
            SysManagerFragments.addToSysFragment(new UserMainProfileMyOrderException(), "UserMainProfileMyOrderException");


            SysManagerFragments.addToSysFragment(new DirectPayMerchantCreate(), "DirectPayMerchantCreate");


        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }


}
